package study.springcloud.gateway.support.exception;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 * 网关异常配置，覆盖默认的异常处理
 */
@Configuration
public class ExceptionHandlerConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public ErrorWebExceptionHandler handler(ObjectProvider<List<ViewResolver>> viewResolverProvider,
                                            ServerCodecConfigurer codecConfigurer) {
        GatewayExceptionHandler handler = new GatewayExceptionHandler();
        //视图解析
        handler.setViewResolvers(viewResolverProvider.getIfAvailable(Collections::emptyList));
        //消息读
        handler.setMessageWriters(codecConfigurer.getWriters());
        //消息写
        handler.setMessageReaders(codecConfigurer.getReaders());
        return handler;
    }
}
